//
//  PagingViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 8/4/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit

public class PagingViewController: UIViewController, UIScrollViewDelegate {
    
    var viewControllers: [UIViewController] = []
    var contentScrollView = UIScrollView()
    
    var currentIndex = 0
    
    public init(viewControllers: [UIViewController], frame: CGRect) {
        super.init(nibName: nil, bundle: nil)
        self.viewControllers = viewControllers
        
        self.view.frame = frame
    }
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        
        setUpContentView()
    }
    
    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    func setUpContentView() {
        contentScrollView.frame = self.view.bounds
        contentScrollView.pagingEnabled = true
        contentScrollView.scrollsToTop = false
        contentScrollView.translatesAutoresizingMaskIntoConstraints = false
        contentScrollView.alwaysBounceHorizontal = true
        contentScrollView.showsHorizontalScrollIndicator = false
        contentScrollView.showsVerticalScrollIndicator = false
        contentScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * CGFloat(viewControllers.count), 0.0)
        
        configureUserInterface()
        
        self.view.addSubview(contentScrollView)
    }
    
    
    func configureUserInterface() {
        contentScrollView.delegate = self
        
        for var i = 0; i < viewControllers.count; i++ {
            addPageAtIndex(i)
        }
        
    }
    
    
    func add(viewController vc:UIViewController, atIndex index: Int) {
        vc.willMoveToParentViewController(self)
        vc.view.frame = CGRectMake(self.view.frame.width * CGFloat(index), 0, self.view.frame.width, self.view.frame.height)
        
        self.addChildViewController(vc)
        self.contentScrollView.addSubview(vc.view)
        
        vc.didMoveToParentViewController(self)
    }
    
    
    func addPageAtIndex(index : Int) {
        
        let vc = viewControllers[index]
        
        add(viewController: vc, atIndex: index)
    }


    // MARK: - Navigation

    override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
    }
}
